package com.lemo.smart.helper;

import com.lemo.smart.annotation.RequestMapping;
import com.lemo.smart.bean.Handler;
import com.lemo.smart.bean.Request;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.ArrayUtils;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

/**
 * 控制器助手类
 * Created by 罗选通 on 2017/12/22.
 */
public class ControllerHelper {

  private static final Map<Request, Handler> ACTION_MAP = new HashedMap();

  static {
    //获取所有的controller类
    Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
    if (CollectionUtils.isNotEmpty(controllerClassSet)) {
      //遍历controller
      for (Class<?> controllerClass : controllerClassSet) {
        //获取controller中定义的方法
        Method[] methods = controllerClass.getDeclaredMethods();
        if (!ArrayUtils.isEmpty(methods)) {
          //遍历controller中的方法
          for (Method method : methods) {
            //判断方法上是否有@RequestMapping注解
            if (method.isAnnotationPresent(RequestMapping.class)) {
              //从注解中去除url映射规则
              RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
              String mapping = requestMapping.value();
              //验证url映射规则
              if (mapping.matches("\\w+:/\\w*")) {
                String[] array = mapping.split(":");
                if (!ArrayUtils.isEmpty(array) && array.length == 2) {
                  //获取请求方法和请求路径
                  String requestMethod = array[0];
                  String requestPath = array[1];
                  Request request = new Request(requestMethod, requestPath);
                  Handler handler = new Handler(controllerClass, method);
                  ACTION_MAP.put(request, handler);
                }
              }
            }
          }
        }
      }
    }
  }

  /**
   *  获取Handler
   * @param requestMethod
   * @param requestPath
   * @return
   */
  public static Handler getHandler(String requestMethod, String requestPath) {
    Request request = new Request(requestMethod, requestPath);
    return ACTION_MAP.get(request);
  }

}
